package operate;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import operate.vo.Dict;
import operate.vo.Type;
import util.Log;

import component.Text;

import db.JdbcOperate;



public class DictOperate extends JdbcOperate {

	private static Map<String, List<Dict>> dicts = new HashMap<String, List<Dict>>();
	private static Map<String, Type> dictTypes = new HashMap<String, Type>();
public static Text cb=new Text();
	public static void setDict(Type type) {
		List list = new ArrayList<Dict>();
		dicts.put(type.getCode(), list);
	}

	public static List<Dict> getDictBycode(String key) {
		return (List) dicts.get(key);
	}

	public static Type getDictTypeBycode(String key) {
		return dictTypes.get(key);
	}

	public void initDict() {
		List<Type> list = findDictType();
		List<Dict> ds = null;
		String code = null;
		for (Type type : list) {
			Log.write(2, null, "初始化字典：" + type.getCode(), null);
			code = type.getCode();
			ds = findDict(type.getCode());
			dicts.put(code, ds);
		}

	}

	public List findDict(String code) {
		List<Dict> dicts = new ArrayList<Dict>();
		try {
			List<Map> list = query("select * from dict t where t.isdelete=0 and code='"
					+ code + "'");
			for (Map map : list) {
				Dict dict = new Dict();
				dict.setId(map.get("ID").toString());
				dict.setName(map.get("NAME").toString());
				dict.setValue(map.get("VALUE").toString());
				dicts.add(dict);
			}
		} catch (SQLException e) {
			Log.write(3, DictOperate.class, "查询字典出现异常", e);
		}
		return dicts;
	}

	private List findDictType() {
		List<Type> types = new ArrayList<Type>();
		try {
			List<Map> list = query("select * from DICT_TYPE t ");
			for (Map map : list) {
				Type t = new Type();
				t.setCode(map.get("CODE").toString());
				t.setTypeName(map.get("TYPE_NAME").toString());
				t.setDefaultValue(map.get("DEFAULT_VALUE").toString());
				dictTypes.put(t.getCode(), t);
				types.add(t);
			}
		} catch (SQLException e) {
			Log.write(3, DictOperate.class, "查询字典类型出现异常", e);
		}
		return types;
	}

	public void addDictType(Type type) {
		String sql = "insert into dict_type(type_name,code,default_name) values('"
				+ type.getTypeName()
				+ "','"
				+ type.getCode()
				+ "','"
				+ type.getDefaultValue() + "')";
		try {
			insertOrUpdate(sql);
			setDict(type);
		} catch (SQLException e) {
			Log.write(3, DictOperate.class, "添加字典类型出现异常", e);
		}

	}

	public static Map<String, Type> getDictTypes() {
		return dictTypes;
	}

}
